<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>{{ greetingMessage }}</h2>
    </div>
    <div class="chat-body">
      <!-- 循环渲染对话记录 -->
      <div v-for="(chatRecord, index) in chatRecords" :key="index" class="chat-content clearfix">
        <div class="chat-question" style="font-size:17px">{{ chatRecord.question }}</div>
        <div class="chat-answer">
          <!-- 只有当前正在加载的对话才显示加载图标 -->
          <div v-if="isLoading && index === chatRecords.length - 1">
            <img class="loading" src="@/assets/images/loading.svg" alt="">
          </div>
          <div v-if="!isLoading && chatRecord.displayedAnswer" style="font-size:17px">
            {{ chatRecord.displayedAnswer }}
          </div>
        </div>
      </div>
      <div v-if="chatResponse" class="chat-response">
        <div class="ai-response">
          <span class="ai-name">AI 回复：</span>
          <p>{{ chatResponse }}</p>
        </div>
      </div>
      <div class="chat-input-area">
        <textarea
          v-model="chatInput"
          placeholder="请输入聊天内容"
          class="chat-input"
          :style="{ height: textareaHeight + 'px' }"
          @input="adjustTextareaHeight"
          @paste="adjustTextareaHeight"
          @keydown.enter.prevent="handleEnterKey"
          style="resize: none;"
        />
        <button @click="chat" class="send-button" :disabled="changeIsEmpty" :style="btnStyle">发送</button>
      </div>
    </div>    
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      chatInput: '',
      chatResponse: null,
      textareaHeight: 60,
      minHeight: 60,
      maxHeight: 500,
      greetingMessage: '',
      // 存储对话记录的数组
      chatRecords: [],
      isLoading: false,
      typingTimer: null
    };
  },
  mounted() {
    this.updateGreetingMessage();
  },
  computed: {
    btnStyle() {
      return this.chatInput.trim() === '' ? { cursor: 'not-allowed' } : {};
    },
    changeIsEmpty() {
      return this.chatInput.trim() === '';
    }
  },
  methods: {
    async chat() {
      if (this.chatInput.trim() === '') {
        return;
      }
      this.isLoading = true;
      console.log(this.chatInput);

      const data = {
        prompt: this.chatInput
      };

      // 创建新的对话记录对象
      const newChatRecord = {
        question: this.chatInput,
        answer: '',
        displayedAnswer: ''
      };
      // 将新的对话记录添加到数组中
      this.chatRecords.push(newChatRecord);

      const response = await this.$store.dispatch("BaiduChat", data)
      console.log(response);
      if (response.code === 0) {
        try {
          const parsedData = JSON.parse(response.data);
          if (parsedData.choices && parsedData.choices.length > 0) {
            // 获取最新的对话记录
            const currentChatRecord = this.chatRecords[this.chatRecords.length - 1];
            currentChatRecord.answer = parsedData.choices[0].message.content;
            // 隐藏加载效果
            this.isLoading = false;
            // 开始打字效果
            this.startTypingEffect(currentChatRecord);
          } else {
            this.$message.error('未获取到有效的回复内容');
            this.isLoading = false;
          }
        } catch (parseError) {
          console.error('解析响应数据时出错:', parseError);
          this.$message.error('解析响应数据时出错，请稍后再试');
          this.isLoading = false;
        }
      } else {
        this.$message.error('请求失败，请稍后再试');
        this.isLoading = false;
      }
      this.chatInput = '';
      this.adjustTextareaHeight();
    },
    startTypingEffect(chatRecord) {
      let index = 0;
      this.typingTimer = setInterval(() => {
        if (index < chatRecord.answer.length) {
          chatRecord.displayedAnswer += chatRecord.answer[index];
          index++;
        } else {
          clearInterval(this.typingTimer);
        }
      }, 50); // 每 50 毫秒显示一个字符，可以根据需要调整
    },
    adjustTextareaHeight() {
      const tempTextarea = document.createElement('textarea');
      tempTextarea.value = this.chatInput;
      tempTextarea.style.fontSize = window.getComputedStyle(document.querySelector('.chat-input')).fontSize;
      tempTextarea.style.padding = window.getComputedStyle(document.querySelector('.chat-input')).padding;
      tempTextarea.style.width = window.getComputedStyle(document.querySelector('.chat-input')).width;
      document.body.appendChild(tempTextarea);
      let contentHeight = tempTextarea.scrollHeight;
      if (contentHeight < this.minHeight) {
        contentHeight = this.minHeight;
      } else if (contentHeight > this.maxHeight) {
        contentHeight = this.maxHeight;
      }
      this.textareaHeight = contentHeight;

      document.body.removeChild(tempTextarea);
    },
    handleEnterKey(event) {
      if (this.chatInput.trim()!== '') {
        this.chat();
      }
    },
    updateGreetingMessage() {
      const userInfo = JSON.parse(localStorage.getItem('sessionForm'));
      const userName = userInfo && userInfo.uaccount ? userInfo.uaccount : '用户';
      const currentHour = new Date().getHours();
      let timePeriod = '';

      if (currentHour >= 5 && currentHour < 12) {
        timePeriod = '早上';
      } else if (currentHour >= 12 && currentHour < 14) {
        timePeriod = '中午';
      } else if (currentHour >= 14 && currentHour < 18) {
        timePeriod = '下午';
      } else {
        timePeriod = '晚上';
      }

      this.greetingMessage = ` ${timePeriod}好！请告诉我你遇到的问题，我会尽力帮助你。`;
    }
  }
};
</script>

<style scoped>
/* 整体容器 */
.chat-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  background: linear-gradient(to bottom, #f0f8ff, #e0efff);
  padding: 20px;
  box-sizing: border-box;
}

/* 头部 */
.chat-header {
  width: 100%;
  margin-bottom: 30px;
  text-align: center;
}

.chat-header h2 {
  font-size: 32px;
  color: #409eff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  animation: fadeIn 1s ease-in-out;
}

/* 主体内容 */
.chat-body {
  width: 100%;
  max-width: 800px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 30px;
  border-radius: 15px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  animation: slideInUp 1s ease-in-out;
}

/* 回复区域 */
.chat-response {
  margin-bottom: 30px;
  animation: fadeInUp 1s ease-in-out;
}

.ai-response {
  background-color: #e3f2fd;
  padding: 20px;
  border-radius: 12px;
  border: 2px solid #90caf9;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.ai-name {
  font-weight: bold;
  color: #1976d2;
  font-size: 18px;
  margin-bottom: 10px;
  display: inline-block;
}

.ai-response p {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  margin: 0;
}

/* 输入区域 */
.chat-input-area {

  width: 100%;
}

.chat-input {
  flex: 1;
  padding: 15px;
  margin-bottom: 15px;
  border: 2px solid #ccc;
  border-radius: 8px;
  font-size: 18px;
  outline: none;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  overflow-y: auto;
  width: 100%;
}
.chat-input-area button {
  display: block;
  margin: 0 auto;
  width: 80%;
}

.chat-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 8px rgb(64, 158, 255, .6);
}

.send-button {
  padding: 15px 30px;
  background-color: rgb(64, 158, 255, .6);
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.2s ease;
}

.send-button:hover {
  background-color: rgb(64, 158, 255, 1);
  transform: scale(1.05);
}

/* 动画定义 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideInUp {
  from {
    transform: translateY(20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 600px) {
  .chat-body {
    padding: 20px;
  }

  .chat-input-area {
    flex-direction: column;
  }

  .chat-input,
  .send-button {
    width: 100%;
  }
}

.chat-content {
  margin-bottom: 100px;
}
.clearfix::after {
      content: "";
      display: block;
      clear: both;
    }
.chat-question {
  padding: 10px;
  float: right;
  background-color: #e9f4ff;
  border-radius: 10px;
}
.chat-answer {
  float: left;
  margin-top: 80px;  
}
@keyframes loading {
  0% {
    transform: rotateX(40deg) rotateY(40deg);
  }
  50% {
    transform: rotateX(180deg) rotateY(180deg); /* 旋转180度，实现上下位置交换 */
  }
  100% {
    transform: rotateX(-40deg) rotateY(-45deg);
  }
}
.loading {
  animation: loading 3s ease-in-out infinite;
  transform-style: preserve-3d;
}
</style>